<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/25
 * Time: 8:30
 */

namespace app\api\controller\v1;

use app\api\model\User;
use app\api\model\UserAddress;
use app\api\service\Token as TokenService;
use app\lib\Exception\UserException;
use app\lib\Validate\AddressValidate;

class AddressController extends BaseController
{
    public function getUserAddress()
    {
        $uid = TokenService::getUid();
        $userAddress = UserAddress::getUserAddres($uid);
        if(!$userAddress) {
            throw new UserException([
                'message' => '没有找到地址诶',
                'code' => 404,
                'error' => 10005
            ]);
        }
        return $userAddress;
    }

    public function createOrUpdateAddress()
    {
        $validate = new AddressValidate();
        $validate->goCheck();
        $uid = TokenService::getUid();
        $user = User::get($uid);

        if(!$user){
            throw new UserException();
        }

        $userAddress = $user->address;
        $data = input('post.');
        $validate->getByDateRule($data);

        if(!$userAddress) {
            $user->address()->save($data);
        }else{
            $user->address->save($data);
        }
    }
}